package com.df.gameserver.modules.user;

import com.df.gameserver.modules.user.entity.Player;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

import java.util.concurrent.ConcurrentHashMap;

public class UserManager {
    private enum Single {
        /**
         * 单例对象的实例
         */
        INSTANCE;
        private UserManager instance;

        Single() {
            this.instance = new UserManager();
        }
    }

    public  AttributeKey<String> userIdKey = AttributeKey.newInstance("userId");
    public static UserManager getInstance() {
        return UserManager.Single.INSTANCE.instance;
    }

    private UserManager() {
    }

    private final ConcurrentHashMap<String, Player> id2user = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, Channel> id2channel = new ConcurrentHashMap<>();

    public ConcurrentHashMap<String, Player> getId2user() {
        return id2user;
    }

    public ConcurrentHashMap<String, Channel> getId2channel() {
        return id2channel;
    }


    public Player getPlayer(String userId) {
        if(userId==null){
            return null;
        }
        return id2user.get(userId);
    }
    public boolean addUser(Player player) {
        if (player == null || player.getId().isEmpty()) {
            return false;
        }
        id2user.put(player.getId(), player);
        return true;
    }
    public boolean addChannel(Player player,Channel channel) {
        if (player == null || player.getId().isEmpty()) {
            return false;
        }
        if(channel==null){
            return false;
        }
        id2channel.put(player.getId(), channel);
        return true;
    }

    public boolean removeUser(Player player) {
        if (player == null) {
            return false;
        }
        return removeUser(player.getId());
    }

    public boolean removeUser(String userId) {
        if (userId == null || userId.isEmpty()) {
            return false;
        }
        id2user.remove(userId);
        id2channel.remove(userId);
        return true;
    }

    public Channel getChannel(Player player) {
        if (player == null) {
            return null;
        }
        return getChannel(player.getId());
    }

    public Channel getChannel(String userId) {
        if (userId == null || userId.isEmpty()) {
            return null;
        }
        return id2channel.get(userId);
    }

}
